package com.yanqu.road.server.manger.activity.strongholdwar;

import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.activity.UnionActivityConditionData;
import com.yanqu.road.entity.activity.UserActivityConditionData;
import com.yanqu.road.entity.enums.eBigRankType;
import com.yanqu.road.entity.player.UserInfo;
import com.yanqu.road.entity.rank.UnionActivityRank;
import com.yanqu.road.entity.rank.UserRank;
import com.yanqu.road.entity.task.args.UnionRiseRankArgs;
import com.yanqu.road.entity.union.UnionBaseInfo;
import com.yanqu.road.entity.union.UnionInfo;
import com.yanqu.road.entity.union.cross.CrossUnionMember;
import com.yanqu.road.logic.bussiness.player.UserActivityBussiness;
import com.yanqu.road.logic.bussiness.player.activity.UserStrongholdBusiness;
import com.yanqu.road.logic.config.GameConfig;
import com.yanqu.road.logic.helper.UnionHelper;
import com.yanqu.road.logic.pb.PlayerBasePb;
import com.yanqu.road.logic.pb.UnionBasePb;
import com.yanqu.road.logic.rank.RankListModel;
import com.yanqu.road.logic.rank.UnionActivityRankListModel;
import com.yanqu.road.pb.crossunion.activity.CrossUnionActivityRankDataProto;
import com.yanqu.road.server.GameServer;
import com.yanqu.road.server.TempMgr;
import com.yanqu.road.server.manger.cross.CrossDataMgr;
import com.yanqu.road.server.manger.player.UserMgr;
import com.yanqu.road.server.manger.player.GamePlayerMgr;
import com.yanqu.road.server.manger.rank.RankMgr;
import com.yanqu.road.server.manger.union.GameUnionActivityGroupMgr;
import com.yanqu.road.server.manger.union.UnionActivityMgr;
import com.yanqu.road.server.manger.union.CrossUnionMgr;
import com.yanqu.road.utils.YanQuMessageUtils;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.server.protocol.CrossProtocol;
import com.yanqu.road.utils.string.StringUtils;

import java.math.BigInteger;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class StrongholdActivityRankMgr extends TempMgr {

//    private static Map<Integer, Map<Integer, RankListModel>> rankListModelMap;

//    private static Map<Integer, Map<Integer, UnionActivityRankListModel>> unionRankListModelMap;

    //activityId conditionType userId
    private static Map<Integer, Map<Integer, Map<Long, UserActivityConditionData>>> unionUserActivityDataMap;
    //activityId conditionType unionId
    private static Map<Integer, Map<Integer, Map<String, UnionActivityConditionData>>> unionConditionDataMap;

    @Override
    public boolean init() throws Exception {
        return reload();
    }

    @Override
    public boolean reloadConfig() throws Exception {
        return true;
    }

    @Override
    public boolean stop() {
        return false;
    }

    @Override
    public boolean save() {
        for (Map<Integer, Map<String, UnionActivityConditionData>> dataMap : unionConditionDataMap.values()) {
            for (Map<String, UnionActivityConditionData> unionActivityConditionDataMap : dataMap.values()) {
                for (UnionActivityConditionData data : unionActivityConditionDataMap.values()) {
                    if (data.isInsertOption()) {
                        UserActivityBussiness.addUnionActivityConditionData(data);
                    } else if (data.isUpdateOption()) {
                        UserActivityBussiness.updateUnionActivityConditionData(data);
                    }
                }
            }
        }
        return true;
    }

    @Override
    public boolean reloadData() {
//        rankListModelMap = new ConcurrentHashMap<>();
//        unionRankListModelMap = new ConcurrentHashMap<>();
        unionConditionDataMap = new ConcurrentHashMap<>();
        unionUserActivityDataMap = new ConcurrentHashMap<>();
        reloadRank();
        return true;
    }

    @Deprecated
    public static RankListModel getRankListModel(int activityId, int type) {
        return null;
//        return rankListModelMap.get(activityId).get(type);
    }

    @Deprecated
    public static UnionActivityRankListModel getUnionRankListModel(int activityId, int type) {
        return null;
//        return unionRankListModelMap.get(activityId).get(type);
    }

    @Deprecated
    public static void removeUnionActivityRank(int activityId, int type, String unionUid) {
        UnionActivityRankListModel unionActivityRankListModel = getUnionActivityRankListModel(activityId, type);
        if (null != unionActivityRankListModel) {
            unionActivityRankListModel.removeRank(unionUid);
        }
    }

    @Deprecated
    public static int getActivityRank(int activityId, int type, long userId) {
        RankListModel rankListModel = getRankListModel(activityId, type);
        if (null != rankListModel) {
            return rankListModel.getMyRank(userId);
        }
        return -1;
    }

    @Deprecated
    public static int getActivityUnionRank(int activityId, int type, String unionUid) {
        UnionActivityRankListModel rankListModel = getUnionRankListModel(activityId, type);
        if (null != rankListModel) {
            return rankListModel.getMyRank(unionUid);
        }
        return -1;
    }

    public static void changeRank(int activityId, int type, UserInfo userInfo, BigInteger value) {
        UserRank userRank = new UserRank();
        userRank.setUserId(userInfo.getUserId());
        userRank.setUserBaseInfo(UserMgr.parseUserBaseInfo(userInfo,
                GameServer.getInstance().getServerId()));
        userRank.setValue(value);
        //上传跨服
        CrossDataMgr.StrongholdRankChange(activityId, type, userRank);
    }

    /**
     * 加载商战活动排行榜
     */
    public static void reloadRank() {
        ActivityInfo activityInfo = StrongholdActivityMgr.getOpenActivityInfo();
        if (null == activityInfo) {
            return;
        }

        unionConditionDataMap.put(activityInfo.getActivityId(), new ConcurrentHashMap<>());
        unionUserActivityDataMap.put(activityInfo.getActivityId(), new ConcurrentHashMap<>());
        List<Integer> unionConditionTypeList = StrongholdActivityMgr.getUnionConditionTypeList();
        for (Integer conditionType : unionConditionTypeList) {
            Map<Long, UserActivityConditionData> tempUserConditionDataMap = UserStrongholdBusiness.getUserActivityConditionTypeDataMap(
                    activityInfo.getActivityId(), conditionType);
            Map<String, UnionActivityConditionData> tempUnionConditionDataMap = UserActivityBussiness.getUnionActivityConditionDataMap(activityInfo.getActivityId(), conditionType);
            UnionActivityMgr.checkUnionActivityConditionData(tempUserConditionDataMap, tempUnionConditionDataMap);
            unionConditionDataMap.get(activityInfo.getActivityId()).put(conditionType, tempUnionConditionDataMap);
            unionUserActivityDataMap.get(activityInfo.getActivityId()).put(conditionType, tempUserConditionDataMap);
        }
    }

    public static void changeUnionActivityValue(int activityId, int type, String unionUid, long userId, UserActivityConditionData userConditionData, int notifyType) {
        UnionInfo unionInfo = CrossUnionMgr.getUnionInfo(unionUid);
        if (null != unionInfo) {
            int groupId = GameUnionActivityGroupMgr.getGroupId(activityId, unionUid);
            ActivityInfo inTimeActivityInfo = StrongholdActivityMgr.getInTimeActivityInfo(activityId);
            //属于活动开始和结束时间
            if (null != inTimeActivityInfo && activityId == inTimeActivityInfo.getActivityId()&& !StrongholdActivityMgr.isGameFinish()) {
                if (userConditionData == null) {
                        Map<Integer, List<UserActivityConditionData>> dataMap = StrongholdActivityMgr.getUserActivityConditionDataMap(userId,activityId);
                        if (dataMap != null) {
                            List<UserActivityConditionData> dataList = dataMap.get(type);
                            if (dataList != null) {
                                for (UserActivityConditionData data : dataList) {
                                    userConditionData = data;
                                }
                            }
                        }
                }
                checkUnionConditionData(activityId, unionUid);
                UnionActivityConditionData unionActivityConditionData;
                synchronized (unionConditionDataMap) {
                    unionActivityConditionData = getUnionActivityConditionData(activityId, unionUid, unionInfo, unionConditionDataMap, type);
                    if (UnionRiseRankArgs.NOTIFY_TYPE_NORMAL == notifyType || UnionRiseRankArgs.NOTIFY_TYPE_JOIN == notifyType) {
                        if (null != userConditionData) {
                            unionActivityConditionData.addMemberUserId(userConditionData.getUserId());
                            setUserActivityConditionData(userConditionData);
                            UnionActivityMgr.changeUnionMemberPositionData(unionUid,userId,unionActivityConditionData);
                        }
                    } else if (UnionRiseRankArgs.NOTIFY_TYPE_REMOVE == notifyType || UnionRiseRankArgs.NOTIFY_TYPE_DELETE == notifyType) {
                        unionActivityConditionData.removeMemberUserId(userId);
                        unionActivityConditionData.removeMemberPosition(userId);
                    } else if(UnionRiseRankArgs.NOTIFY_TYPE_POSITION_CHANGE == notifyType){
                        UnionActivityMgr.changeUnionMemberPositionData(unionUid,userId,unionActivityConditionData);
                    }
                    UnionActivityMgr.calcUnionActivityConditionValue(unionActivityConditionData, getUserActivityConditionDataMap(activityId, type));
                }
                CrossUnionActivityRankDataProto.CrossUnionActivityUserDataMsg.Builder msg = CrossUnionActivityRankDataProto.CrossUnionActivityUserDataMsg.newBuilder();
                if (userConditionData == null) {
                    msg.setUserId(0);
                    msg.setValue("0");
                }else {
                    msg.setUserId(userId);
                    msg.setValue(userConditionData.getValue().toString());
                    msg.setUserBaseInfo(PlayerBasePb.parsePlayerBaseTempMsg(UserMgr.getUserBaseInfo(userId, GameServer.getInstance().getServerId())));
                }
                msg.setActivityId(activityId);
                msg.setConditionType(type);
                msg.setUnionId(unionUid);
                msg.setChangeType(notifyType);
                Map<Long, Integer> positionMap = CrossUnionMgr.getMemberPositionMap(unionUid);
                for (Map.Entry<Long, Integer> entry : positionMap.entrySet()) {
                    Long memberId = entry.getKey();
                    Integer pos = entry.getValue();
                    CrossUnionActivityRankDataProto.CrossUnionMemberPosDataMsg.Builder builder = CrossUnionActivityRankDataProto.CrossUnionMemberPosDataMsg.newBuilder();
                    builder.setPos(pos);
                    builder.setUserId(memberId);
                    msg.addMember(builder);
                }
                msg.setUnionServerId(CrossUnionMgr.getUnionServerId(unionUid));
                UnionBaseInfo unionBaseInfo = CrossUnionMgr.parseUnionBaseInfo(unionUid);
                if (unionBaseInfo != null) {
                    msg.setUnionBaseInfo(UnionBasePb.parseUnionBaseTempMsg(unionBaseInfo));
                }
                if (!CrossUnionMgr.isAllSync()) {
                    return;
                }
                GamePlayerMgr.sendUnionActivityGroupPacket(CrossProtocol.C_CROSS_UNION_ACTIVITY_GROUP_USER_VALUE_CHANGE, msg, 0, activityId, groupId);
            }
        }
    }

    public static void changeUnionActivityValueNotUpload(int activityId, int type, String unionUid, long userId, UserActivityConditionData userConditionData, int notifyType) {
        UnionInfo unionInfo = CrossUnionMgr.getUnionInfo(unionUid);
        if (null != unionInfo) {
            int groupId = GameUnionActivityGroupMgr.getGroupId(activityId, unionUid);
            ActivityInfo inTimeActivityInfo = StrongholdActivityMgr.getInTimeActivityInfo(activityId);
            //属于活动开始和结束时间
            if (null != inTimeActivityInfo && activityId == inTimeActivityInfo.getActivityId() && !StrongholdActivityMgr.isGameFinish()) {
                if (userConditionData == null) {
                    Map<Integer, List<UserActivityConditionData>> dataMap = StrongholdActivityMgr.getUserActivityConditionDataMap(userId,activityId);
                    if (dataMap != null) {
                        List<UserActivityConditionData> dataList = dataMap.get(type);
                        if (dataList != null) {
                            for (UserActivityConditionData data : dataList) {
                                userConditionData = data;
                            }
                        }
                    }
                }
                checkUnionConditionData(activityId, unionUid);
                UnionActivityConditionData unionActivityConditionData;
                synchronized (unionConditionDataMap) {
                    unionActivityConditionData = getUnionActivityConditionData(activityId, unionUid, unionInfo, unionConditionDataMap, type);
                    if (UnionRiseRankArgs.NOTIFY_TYPE_NORMAL == notifyType || UnionRiseRankArgs.NOTIFY_TYPE_JOIN == notifyType) {
                        if (null != userConditionData) {
                            unionActivityConditionData.addMemberUserId(userConditionData.getUserId());
                            setUserActivityConditionData(userConditionData);
                            UnionActivityMgr.changeUnionMemberPositionData(unionUid,userId,unionActivityConditionData);
                        }
                    } else if (UnionRiseRankArgs.NOTIFY_TYPE_REMOVE == notifyType || UnionRiseRankArgs.NOTIFY_TYPE_DELETE == notifyType) {
                        unionActivityConditionData.removeMemberUserId(userId);
                        unionActivityConditionData.removeMemberPosition(userId);
                    } else if(UnionRiseRankArgs.NOTIFY_TYPE_POSITION_CHANGE == notifyType){
                        UnionActivityMgr.changeUnionMemberPositionData(unionUid,userId,unionActivityConditionData);
                    }
                    UnionActivityMgr.calcUnionActivityConditionValue(unionActivityConditionData, getUserActivityConditionDataMap(activityId, type));
                }

                CrossUnionActivityRankDataProto.CrossUnionActivityUserDataMsg.Builder msg = CrossUnionActivityRankDataProto.CrossUnionActivityUserDataMsg.newBuilder();

                if (userConditionData == null) {
                    msg.setUserId(0);
                    msg.setValue("0");
                }else {
                    msg.setUserId(userId);
                    msg.setValue(userConditionData.getValue().toString());
                    msg.setUserBaseInfo(PlayerBasePb.parsePlayerBaseTempMsg(UserMgr.getUserBaseInfo(userId, GameServer.getInstance().getServerId())));
                }
                msg.setActivityId(activityId);
                msg.setConditionType(type);
                msg.setUnionId(unionUid);
                msg.setChangeType(notifyType);
                Map<Long, Integer> positionMap = CrossUnionMgr.getMemberPositionMap(unionUid);
                for (Map.Entry<Long, Integer> entry : positionMap.entrySet()) {
                    Long memberId = entry.getKey();
                    Integer pos = entry.getValue();
                    CrossUnionActivityRankDataProto.CrossUnionMemberPosDataMsg.Builder builder = CrossUnionActivityRankDataProto.CrossUnionMemberPosDataMsg.newBuilder();
                    builder.setPos(pos);
                    builder.setUserId(memberId);
                    msg.addMember(builder);
                }
                msg.setUnionServerId(CrossUnionMgr.getUnionServerId(unionUid));
                UnionBaseInfo unionBaseInfo = CrossUnionMgr.parseUnionBaseInfo(unionUid);
                if (unionBaseInfo != null) {
                    msg.setUnionBaseInfo(UnionBasePb.parseUnionBaseTempMsg(unionBaseInfo));
                }
                if (!CrossUnionMgr.isAllSync()) {
                    return;
                }
                GamePlayerMgr.sendUnionActivityGroupPacket(CrossProtocol.C_CROSS_UNION_ACTIVITY_GROUP_USER_VALUE_CHANGE, msg, 0, activityId, groupId);

            }
        }
    }
/*
    public static void changeUnionActivityValueDirectly(int activityId, int type, String unionUid, long userId, int notifyType, String score) {
        UnionInfo unionInfo = CrossUnionMgr.getUnionInfo(unionUid);
        if (null != unionInfo) {
            ActivityInfo inTimeActivityInfo = StrongholdActivityMgr.getInTimeActivityInfo(activityId);
            //属于活动开始和结束时间
            if (null != inTimeActivityInfo && activityId == inTimeActivityInfo.getActivityId()) {
                checkUnionConditionData(activityId, unionUid);
                UnionActivityConditionData unionActivityConditionData;
                synchronized (unionConditionDataMap) {
                    unionActivityConditionData = getUnionActivityConditionData(activityId, unionUid, unionInfo, unionConditionDataMap, type);
                    if (UnionRiseRankArgs.NOTIFY_TYPE_NORMAL == notifyType || UnionRiseRankArgs.NOTIFY_TYPE_JOIN == notifyType) {
                        if (userId > 0) {
                            unionActivityConditionData.addMemberUserId(userId);
                        }
                    } else if (UnionRiseRankArgs.NOTIFY_TYPE_REMOVE == notifyType || UnionRiseRankArgs.NOTIFY_TYPE_DELETE == notifyType) {
                        unionActivityConditionData.removeMemberUserId(userId);
                    }
                    if (StringUtils.isNullOrEmpty(score)) {
                        unionActivityConditionData.setValue(new BigInteger(score));
                        unionActivityConditionData.setLastUpdateTime(System.currentTimeMillis());
                    }
                }
                UnionActivityRankListModel unionActivityRankListModel = getUnionActivityRankListModel(activityId, type);
                if (null != unionActivityRankListModel) {
                    if (unionActivityConditionData.getMemberUserCount() > 0) {
                        UnionActivityRank unionRank = unionActivityRankListModel.rankChange(unionActivityConditionData);
                        if (null != unionRank) {
                        //    CrossDataMgr.strongholdUnionRankChange(activityId, type, unionRank);
                        }
                    } else {
                        unionActivityRankListModel.removeRank(unionUid);
                    }
                }
            }
        }
    }*/

    private static UnionActivityConditionData getUnionActivityConditionData(int activityId, String unionUid, UnionInfo unionInfo, Map<Integer, Map<Integer, Map<String, UnionActivityConditionData>>> unionConditionDataMap, int type) {
        Map<Integer, Map<String, UnionActivityConditionData>> conditionMap = unionConditionDataMap.get(activityId);
        if (conditionMap == null) {
            conditionMap = new ConcurrentHashMap<>();
            unionConditionDataMap.put(activityId, conditionMap);
        }
        Map<String, UnionActivityConditionData> dataMap = conditionMap.get(type);
        if (dataMap == null) {
            dataMap = new ConcurrentHashMap<>();
            conditionMap.put(type, dataMap);
        }
        UnionActivityConditionData unionActivityConditionData = dataMap.get(unionUid);
        if (unionActivityConditionData == null) {
            unionActivityConditionData = new UnionActivityConditionData();
            unionActivityConditionData.setActivityId(activityId);
            unionActivityConditionData.setGetReward(false);
            unionActivityConditionData.setUnionUid(unionInfo.getUnionUid());
            unionActivityConditionData.setInfo("{}");
            unionActivityConditionData.setLastUpdateTime(System.currentTimeMillis() / 1000);
            unionActivityConditionData.setConditionType(type);
            Map<Long, CrossUnionMember> unionMemberMap = CrossUnionMgr.getUnionMemberMap(unionUid);
            if (unionMemberMap != null) {
                for (Long userId : unionMemberMap.keySet()) {
                    UnionActivityMgr.changeUnionMemberPositionData(unionUid,userId,unionActivityConditionData);
                    unionActivityConditionData.addMemberUserId(userId);
                }
            }

            unionActivityConditionData.setInsertOption();
            dataMap.put(unionUid, unionActivityConditionData);
        }
        unionActivityConditionData.setUnionBaseInfo(UnionHelper.parseUnionBaseInfo(unionInfo,UserMgr.getUserInfo(unionInfo.getMasterUserId()), GameServer.getInstance().getServerId()));
        return unionActivityConditionData;
    }

    @Deprecated
    public static UnionActivityRankListModel getUnionActivityRankListModel(Integer activityId, int type) {
        return null;
//        return unionRankListModelMap.get(activityId).get(type);
    }

    public static Map<Long, UserActivityConditionData> getUserActivityConditionDataMap(int activityId, int type) {
        return unionUserActivityDataMap.get(activityId).get(type);
    }

    public static UserActivityConditionData getUserActivityConditionData(int activityId, int type, long userId) {
        Map<Long, UserActivityConditionData> dataMap = getUserActivityConditionDataMap(activityId, type);
        if (null != dataMap) {
            return dataMap.get(userId);
        }
        return null;
    }

    public static void setUserActivityConditionData(UserActivityConditionData userActivityConditionData) {
        if (null == userActivityConditionData) {
            return;
        }
        checkUnionUserConditionData(userActivityConditionData.getActivityId());
        Map<Long, UserActivityConditionData> dataMap = getUserActivityConditionDataMap(userActivityConditionData.getActivityId(), userActivityConditionData.getType());
        if (null != dataMap) {
            dataMap.put(userActivityConditionData.getUserId(), userActivityConditionData);
        }
    }

    public static UnionActivityConditionData getUnionActivityConditionData(int activityId, int type, String unionUid) {
        Map<String, UnionActivityConditionData> dataMap = getUnionActivityConditionDataMap(activityId, type);
        if (null != dataMap) {
            return dataMap.get(unionUid);
        }
        return null;
    }

    public static Map<String, UnionActivityConditionData> getUnionActivityConditionDataMap(int activityId, int type) {
        return unionConditionDataMap.get(activityId).get(type);
    }

    public static UnionActivityConditionData getUnionActivityConditionData(int activityId, int type, long userId) {
        Map<String, UnionActivityConditionData> dataMap = getUnionActivityConditionDataMap(activityId, type);
        if (null != dataMap) {
            for (UnionActivityConditionData unionActivityConditionData : dataMap.values()) {
                if (unionActivityConditionData.hasMemberUserId(userId)) {
                    return unionActivityConditionData;
                }
            }
        }
        return null;
    }

    private static void checkUnionUserConditionData(int activityId) {
        if (!unionUserActivityDataMap.containsKey(activityId)) {
            synchronized (unionUserActivityDataMap) {
                if (!unionUserActivityDataMap.containsKey(activityId)) {
                    unionUserActivityDataMap.put(activityId, new ConcurrentHashMap<>());
                }
            }
        }
    }

    private static void checkUnionConditionData(int activityId, String unionUid) {
        if (!StringUtils.isNullOrEmpty(unionUid)) {
            if (!unionConditionDataMap.containsKey(activityId)) {
                synchronized (unionConditionDataMap) {
                    if (!unionConditionDataMap.containsKey(activityId)) {
                        unionConditionDataMap.put(activityId, new ConcurrentHashMap<>());
                    }
                }
            }
        }
    }
}
